import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:litetoolbox/widgets/animated_scale.dart';
import 'package:litetoolbox/widgets/custom_dialog.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'home_page.dart';
import 'splash_icon.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({Key key}) : super(key: key);

  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  ///显示图标
  bool _showIcon;

  ///请求权限
  Future<bool> _premission() async {
    bool _pre = true;

    ///请求位置权限
    await Permission.locationWhenInUse
        .request()
        .then((s) => _pre = s == PermissionStatus.granted && _pre);

    ///请求麦克风权限
    await Permission.microphone
        .request()
        .then((s) => _pre = s == PermissionStatus.granted && _pre);

    return _pre;
  }

  ///初始化
  Future<void> _ready(BuildContext context) async {
    final SharedPreferences _sp = await SharedPreferences.getInstance();

    final bool _isFirestRun = _sp.getBool('first_run') ?? true;

    if (_isFirestRun)
      await CustomDialog.showTipsDialog(
        context,
        title: '小工具声明',
        content:
            '“小工具”是一款常用工具集合应用，为了相关功能的正常使用，可能需要您授予相关权限。\n定位服务：\n指南针使用。\n录音：\n分贝仪使用。\n小工具全程不需要联网。',

        ///同意使用
        onCheck: () {
          _sp.setBool('first_run', false);
          Navigator.pop(context);
        },

        ///不同意使用
        onCancel: () {
          _sp.setBool('first_run', true);
          SystemNavigator.pop();
        },
      );

    if (await _premission()) {
      ///隐藏图标
      await Future.delayed(const Duration(milliseconds: 500),
          () => setState(() => _showIcon = false));

      ///跳转页面
      Future.delayed(
          const Duration(milliseconds: 500),
          () async => await Navigator.of(context).pushAndRemoveUntil(
              MaterialPageRoute(builder: (_) => const HomePage()),
              (_) => false));
    } else {
      ///如果权限未通过，则退出应用
      SystemNavigator.pop();
    }
  }

  @override
  void initState() {
    super.initState();
    _showIcon = true;
    Future.delayed(const Duration(seconds: 0), () {
      _ready(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        backgroundColor: Colors.black,
        body: Center(
          child: AnimatedScale(
            scale: _showIcon ? 1 : 0,
            duration: const Duration(milliseconds: 500),
            child: const SplashIcon(),
          ),
        ),
      ),
      onWillPop: () => null,
    );
  }
}
